package com.jh.user.business.impl;

import java.util.*;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.CommonConstants;
import com.jh.user.pojo.*;
import com.jh.user.repository.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jh.user.business.UserRoleResourceBusiness;

@Service("userRoleResourceBusiness")
public class UserRoleResourceBusinessImpl implements UserRoleResourceBusiness {

    private final UserRepository userRepository;
    private final JdbcTemplate jdbcTemplate;
    private final ResourceRepository resourceRepository;
    private final RoleResourceRepository roleRes;
    private final RoleRepository roleRepository;

    @Autowired
    public UserRoleResourceBusinessImpl(UserRepository userRepository,
                                        JdbcTemplate jdbcTemplate,
                                        ResourceRepository resourceRepository,
                RoleRepository roleRepository,
                                        RoleResourceRepository roleRes) {
        this.userRepository = userRepository;
        this.jdbcTemplate = jdbcTemplate;
        this.resourceRepository = resourceRepository;
        this.roleRepository = roleRepository;
        this.roleRes = roleRes;
    }

    /*
     *
     * 用户角色管理
     *
     * */
    @Autowired
    private UserRoleRepository userRoleRepository;


    /*
     *推送管理
     * */
    @Autowired
    private JdpushHistoryRepository jdpushHistoryRepository;

    @Autowired
    private PlatformRepository platformRepository;

    private Logger log = LoggerFactory.getLogger(UserRoleResourceBusinessImpl.class);

    /*
     * 权限管理
     */
    @Transactional
    @Override
    public Resource saveResource(Resource resource) {
        return resourceRepository.save(resource);
    }

    @Transactional
    @Override
    public void updateResource(long id, String resourceNo, String resourceName, String url) {

        resourceRepository.updateResourceById(id, resourceNo, resourceName, url);
    }

    @Transactional
    @Override
    public Page<Resource> findAllResource(String resourceNo, String resourceName, String url, Pageable pageable) {
        // TODO Auto-generated method stub
        if (!resourceNo.equals("") && !resourceName.equals("") && !url.equals("")) {
            return resourceRepository.findAllPageResource(resourceNo, resourceName, url, pageable);
        } else if (!resourceNo.equals("") && resourceName.equals("") && url.equals("")) {
            return resourceRepository.findAllPageResourceByNo(resourceNo, pageable);
        } else if (resourceNo.equals("") && !resourceName.equals("") && url.equals("")) {
            return resourceRepository.findAllPageResourceByName(resourceName, pageable);
        } else if (resourceNo.equals("") && resourceName.equals("") && !url.equals("")) {
            return resourceRepository.findAllPageResourceByUrl(url, pageable);
        } else if (!resourceNo.equals("") && !resourceName.equals("") && url.equals("")) {
            return resourceRepository.findAllPageResourceByNoName(resourceNo, resourceName, pageable);
        } else if (!resourceNo.equals("") && resourceName.equals("") && !url.equals("")) {
            return resourceRepository.findAllPageResourceByNoUrl(resourceNo, url, pageable);
        } else if (resourceNo.equals("") && !resourceName.equals("") && !url.equals("")) {
            return resourceRepository.findAllPageResourceByNameUrl(resourceNo, url, pageable);
        }
        return resourceRepository.findAll(pageable);
    }


    @Transactional
    @Override
    public List<Resource> findAllResource(long id) {

        return resourceRepository.findAllResourceById(id);
    }

    @Transactional
    @Override
    public void delResourceById(long id) {
        // TODO Auto-generated method stub
        resourceRepository.delResourceById(id);
    }
    /*
     * 角色权限管理
     */

    //新增角色权限
    @Transactional
    @Override
    public RoleResource saveRoleResource(RoleResource roleResource) {
        // TODO Auto-generated method stub

        List<RoleResource> roleResourceList = roleRes.findResourceByroleid(roleResource.getRoleid(), roleResource.getResourceid());
        if (roleResourceList.size() == 0)
            return roleRes.save(roleResource);
        if (roleResourceList.size() > 0) {
            RoleResource rr = roleResourceList.get(0);
            if (rr.getStatus().equals("1")) {
                return roleRes.updateRoleResourceById(roleResource.getRoleid(), roleResource.getResourceid(), rr.getId());
            }
        }
        return roleResourceList.get(0);
    }

    //查询角色权限
    @Transactional
    @Override
    public Page<RoleResource> findAllRoleResourcePage(long roleid, long resourceid, Pageable pageable) {
        // TODO Auto-generated method stub
        if (roleid != 0 && resourceid != 0) {
            return roleRes.findAllRoleResourcePage(roleid, resourceid, pageable);
        }
        if (roleid == 0 && resourceid != 0) {
            return roleRes.findAllRoleResourcePageByResourceid(resourceid, pageable);
        }
        return roleRes.findAll(pageable);
    }

    //通过角色ID查询资源
    @Transactional
    @Override
    public Page<RoleResourceForm> findAllResourcePageBYRole(long roleid, long resourceid, Pageable pageable) {

        if (roleid != 0 && resourceid != 0) {
            return roleRes.findAllResourcePageById(roleid, resourceid, pageable);
        }
        if (roleid == 0 && resourceid != 0) {
            return roleRes.findAllResourcePageByResourceid(resourceid, pageable);
        }
        if (roleid != 0 && resourceid == 0) {
            return roleRes.findAllResourcePageByRoleID(roleid, pageable);
        }
        return roleRes.findAllResourcePageByAll(pageable);
    }

    //删除权限（物理删除）
    @Transactional
    @Override
    public void delRoleResource(long roleid, long resourceid) {
        // TODO Auto-generated method stub
        roleRes.delRoleResource(roleid, resourceid);
    }


    //修改角色权限
    @Transactional
    @Override
    public void upRoleResource(long roleid, long resourceid, long resourceno) {
        // TODO Auto-generated method stub
        roleRes.updateRoleResourceByRoidReid(roleid, resourceid, resourceno);
    }

    /*
     *
     *角色管理
     * ***/
    //查询所有角色
    @Override
    public List<Role> findAllRole() {
        return roleRepository.findAllRole();
    }

    //查询角色信息
    @Transactional
    @Override
    public Page<Role> rolepage(String rolecode, String rolename, Pageable pageable) {
        // TODO Auto-generated method stub
        if (!rolecode.equals("") && !rolename.equals("")) {
            roleRepository.findAllRole(rolecode, rolename, pageable);

        }
        if (rolecode.equals("") && !rolename.equals("")) {
            roleRepository.findAllRoleByRolename(rolename, pageable);

        }
        if (!rolecode.equals("") && rolename.equals("")) {
            roleRepository.findAllRoleByRolecode(rolecode, pageable);

        }
        return roleRepository.findAll(pageable);
    }



    @Transactional
    @Override
    public List<Role> findAllRole(long id) {

        return roleRepository.findAllRoleById(id);
    }

    //新增角色
    @Transactional
    @Override
    public Role addrole(Role role) {

        return roleRepository.save(role);
    }

    //修改角色
    @Transactional
    @Override
    public void updateRole(long id, String rolename, String rolecode) {
        // TODO Auto-generated method stub
        roleRepository.updateRoleById(id, rolename, rolecode);
    }


    //删除角色
    @Transactional
    @Override
    public void delRole(long id) {
        // TODO Auto-generated method stub
        roleRepository.delRoleById(id);
    }

    /**
     * 用户角色管理
     **/
    //添加用户角色
    @Transactional
    @Override
    public UserRole adduserRole(UserRole role) {

        return userRoleRepository.save(role);
    }

    //查询用户角色
    @Transactional
    @Override
    public Page<UserRole> UserRolepage(long userId, long roleId, Pageable pageable) {
        if (userId != 0 && roleId != 0) {

            return userRoleRepository.findAllUserRole(userId, roleId, pageable);
        }
        if (userId == 0 && roleId != 0) {

            return userRoleRepository.findAllUserRoleByroleId(roleId, pageable);
        }
        if (userId != 0 && roleId == 0) {
            return userRoleRepository.findAllUserRoleByuserId(userId, pageable);
        }
        return userRoleRepository.findAll(pageable);
    }

    //查询用户角色
    public Page<Object> UserRolepageByuserId(long userId, long roleId, Pageable pageable,String phone) {

        if (StringUtils.isNoneBlank(phone)) {
            List<Object> list = new ArrayList<>();
            User user = userRepository.findUserByPhone(phone);
            if (user == null) {
                throw new NullPointerException("没有该用户");
            }else{
                UserRole role = userRoleRepository.queryUserRole(user.getId());
                role.setPhone(user.getPhone());
                list.add(role);
                return new PageImpl<>(list, pageable, list.size());
            }
        } else{
            if (userId != 0) {
               String sql = "select r2.create_time as createTime, r2.role_code as roleCode,r2.role_name as roleName,r2.status,r2.id as roleId,u.phone,u.id as userId " +
                        "from t_user u,t_user_role r,t_role r2 where u.id = r.user_id and r2.id = r.role_id and u.id = " + userId + "  limit  " + pageable.getOffset() + "," +pageable.getPageSize();

                List<UserRole>  list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(UserRole.class));
                String sqlCount = "select  count(1) from t_user u,t_user_role r,t_role r2 where u.id = r.user_id and r2.id = r.role_id and u.id = " + userId;
                List<UserRole>  count = jdbcTemplate.query(sqlCount,new BeanPropertyRowMapper<>(UserRole.class));
                List<Object> result = new ArrayList<>();
                Map<String, String> resMap = new HashMap<>();
                for (UserRole userRole : list) {
                    String userPhone=userRepository.findUserById(userRole.getUserId()).getPhone();
                    userRole.setPhone(userPhone);
                    result.add(userRole);
                }

                return new PageImpl<>(result,pageable,count.size());

            }
            if (roleId != 0) {
                String sql = "select r2.create_time as createTime, r2.role_code as roleCode,r2.role_name as roleName,r2.status,r2.id as roleId,u.phone,u.id as userId " +
                        "from t_user u,t_user_role r,t_role r2 where u.id = r.user_id and r2.id = r.role_id and r2.id = " + roleId + "  limit  " + pageable.getOffset() + "," +pageable.getPageSize();

                List<UserRole>  list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(UserRole.class));
                String sqlCount = "select  count(*) from t_user u,t_user_role r,t_role r2 where u.id = r.user_id and r2.id = " + roleId;
                List<UserRole>  count = jdbcTemplate.query(sqlCount,new BeanPropertyRowMapper<>(UserRole.class));
                List<Object> result = new ArrayList<>();
                Map<String, String> resMap = new HashMap<>();
                for (UserRole userRole : list) {
                    String userPhone=userRepository.findUserById(userRole.getUserId()).getPhone();
                    userRole.setPhone(userPhone);
                    result.add(userRole);
                }

                return new PageImpl<>(result,pageable,count.size());

//                Page<UserRole>  page= userRoleRepository.findAllUserRoleByroleId(roleId,pageable);
//                if(page.getSize()<=0){
//                    throw new NullPointerException("没有该用户");
//                }else{
//
//                    //return userRoleRepository.UserRolepageByuserId(roleId, pageable);
//                    return  userRoleRepository.UserRolepageByroleId(roleId,pageable);
//                }
            }
            String sql = "select r2.create_time as createTime, r2.role_code as roleCode,r2.role_name as roleName,r2.status,r2.id as roleId,u.phone,u.id as userId " +
                    "from t_user u,t_user_role r,t_role r2 where u.id = r.user_id and r2.id = r.role_id  "  + "  limit  " + pageable.getOffset() + "," +pageable.getPageSize();

            List<UserRole>  list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(UserRole.class));
            String sqlCount = "select  count(*) from t_user u,t_user_role r,t_role r2 where u.id = r.user_id" ;
            List<UserRole>  count = jdbcTemplate.query(sqlCount,new BeanPropertyRowMapper<>(UserRole.class));
            List<Object> result = new ArrayList<>();
            Map<String, String> resMap = new HashMap<>();
            for (UserRole userRole : list) {
                String userPhone=userRepository.findUserById(userRole.getUserId()).getPhone();
                userRole.setPhone(userPhone);
                result.add(userRole);
            }

            return new PageImpl<>(result,pageable,count.size());
        }
    }

    public UserRole UserRolepageByRUid(long userId) {
        return userRoleRepository.UserRolepageByRUid(userId);
    }

    /*根据用户ID，角色ID，角色状态查询用户角色*/
    public UserRole findByUserIdAndRoleIdAndStatus(long userId,long roleId,String status){
        return userRoleRepository.findUserRoleByUserIdAndRoleIdAndStatus(userId,roleId,status);
    }

    //修改用户角色
    @Transactional
    @Override
    public void upuserRole(long userId, long roleId) {
        // TODO Auto-generated method stub
        userRoleRepository.updateUserRoleByUserId(userId, roleId);
    }

    //新修改用户角色
    public int newUpdate(long oldUserId,long oldRoleId,long roleId,long brandId,long certigieruserId,String status,Date creatTime){
       return userRoleRepository.newUpdate(oldUserId,oldRoleId,roleId,brandId,certigieruserId,status,creatTime);
    }

    //删除用户角色
    @Transactional
    @Override
    public void delUserRole(long userId) {
        // TODO Auto-generated method stub
        userRoleRepository.delUserRole(userId);
    }

    /**
     * 用户权限
     **/

    public List<User> findAllUser(long id) {
        return roleRepository.findUserById(id);
    }

    //权限查询
    @Transactional
    @Override
    public List<Resource> findUserResourceByuserId(long userId) {
        // TODO Auto-generated method stub
        log.info("权限查询--------------------" + userId);
        return resourceRepository.findUserResourceByuserId(userId);
    }


    /**
     * 推送管理
     ***/
    @Transactional
    @Override
    public JdpushHistory addJdpushHistory(JdpushHistory jdh) {

        return jdpushHistoryRepository.save(jdh);
    }

    /**
     * 推送查询
     */
    @Override
    public Page<JdpushHistory> findJdpushHistoryByuserId(long userId, Pageable pageable) {
        return jdpushHistoryRepository.findJdpushHistoryByuserId(userId, pageable);

    }

    /***
     * 推送删除
     * **/
    @Transactional
    @Override
    public void delJdpushHistoryByuserId(long userId, long brandId, String type) {
        if (type.equals("androidVersion")) {
            jdpushHistoryRepository.delJdpushHistoryByBrandId(brandId, type);
        }


    }

    //通过id删除推送
    @Transactional
    @Override
    public void delJdpushHistoryById(long id) {
        jdpushHistoryRepository.delJdpushHistoryById(id);
    }

    /**
     * 推送查询
     */
    @Override
    public Page<JdpushHistory> findJdpushHistoryByBrandId(long brandId, Pageable pageable) {
        return jdpushHistoryRepository.findJdpushHistoryByBrandId(brandId, pageable);

    }

    /**
     * 删除用户冗余数据
     **/
    @Transactional
    public void delJdpushHistoryByUid(long userid, long brandid) {
        long[] jdpids = jdpushHistoryRepository.findJdpushHistorytop30(userid, brandid);
        if (jdpids != null) {
            if (jdpids.length > 30) {
                long[] jdpids2 = new long[30];
                for (int i = 0; i < 30; i++) {
                    jdpids2[i] = jdpids[i];
                }
                jdpushHistoryRepository.delJdpushHistory(jdpids2, userid, brandid);
            }
        }
    }

    @Override
    public List<UserRole> findUserRoleByRoleid(Long[] usersid, long roleid) {
        return userRoleRepository.findUserRoleByRoleid(usersid, roleid);
    }

	/*@Override
	public Resource findResourceById(String resourceNo) {
		// TODO Auto-generated method stub
		return resourceRepository.findResourceById(resourceNo);
	}*/

    /*
     * 角色权限管理
     */
	/*@Transactional
	@Override
	public RoleResource saveRoleResource(RoleResource roleResource) {
		return roleRes.save(roleResource);
	}

	@Override
	public Page<RoleResource> findAllRoleResourcePage(Pageable pageable) {
		// TODO Auto-generated method stub
		return roleRes.findAllRoleResourcePage(pageable);
	}
*/
	/*@Transactional
	@Override
	public void delRoleResource(long roleid, long resourceid) {
		// TODO Auto-generated method stub
		roleRes.delRoleResource(roleid, resourceid);
	}*/

	/*@Transactional
	@Override
	public void upRoleResource(long roleid, long resourceid,long resourceno) {
		// TODO Auto-generated method stub
		roleRes.upRoleResource(roleid, resourceid,resourceno);
	}


	 * 用户角色管理

	@Override
	public Page<Role> rolepage(Pageable pageable) {
		// TODO Auto-generated method stub
		return rolemanage.findAll(pageable);
	}

	@Override
	public Role addrole(Role role) {
		// TODO Auto-generated method stub
		return rolemanage.save(role);
	}*/

	/*@Transactional
	@Override
	public void updateRole(long id, String rolename) {
		// TODO Auto-generated method stub
		rolemanage.updateRoleById(id, rolename);
	}

	@Transactional
	@Override
	public void delRole(long id) {
		// TODO Auto-generated method stub
		rolemanage.delRoleById(id);
	}*/

    /*
     * 用户角色管理
     */
	/*@Override
	public UserRole adduserRole(UserRole role) {
		// TODO Auto-generated method stub
		return userrole.save(role);
	}

	@Override
	public Page<UserRole> UserRolepage(Pageable pageable) {
		// TODO Auto-generated method stub
		return userrole.findAll(pageable);
	}*/

	/*@Transactional
	@Override
	public void upuserRole(long userId,long roleId) {
		// TODO Auto-generated method stub
		userrole.upuserRole(userId, roleId);
	}

	@Transactional
	@Override
	public void delUserRole(long userId) {
		// TODO Auto-generated method stub
		userrole.deluserRole(userId);
	}
*/
    /**根据userID和status查用户角色*/
    @Override
    public UserRole findByUserIdAndStatus(long userid,String status) {
        return userRoleRepository.findUserRolesByUserIdAndStatus(userid,status);
    }


    public Role findById(long id){
        return roleRepository.findById(id);
    }

    @Override
    public Map<String, Object> queryUserRole(long userId) throws ServiceException {
        Map<String, Object> resMap = new HashMap<>();
        UserRole userRole = userRoleRepository.queryUserRole(userId);
        if (null == userRole) {
            throw new ServiceException("获取用户角色信息失败！");
        }
        long roleId = userRole.getRoleId();
        resMap.put("roleId", roleId);
        return resMap;
    }

    @Override
    public String queryUserIds(long userId) throws ServiceException {
        StringBuffer sb = new StringBuffer(userId + ",");
        Map<String, Object> roleMap = queryUserRole(userId);
        long role = null == roleMap.get("roleId") ? 5L : (Long) roleMap.get("roleId");
        if (CommonConstants.ROLE_ID_06 == role) {
            // 为台卡代理，根据台卡代理查询商铺信息
            User user = userRepository.findUserById(userId);
            if (null == user) {
                throw new ServiceException("获取台卡代理用户信息失败！");
            }
            String phone = user.getPhone();
            if (StringUtils.isEmpty(phone)) {
                throw new ServiceException("获取台卡代理手机号失败！");
            }
            List<Platform> platformList = platformRepository.findByAgent(phone);
            if (null == platformList || platformList.size() == 0) {
                throw new ServiceException("台卡代理信息为空！");
            }
            for (Platform platform : platformList) {
                String shopId = platform.getShopId();
                if (StringUtils.isNotEmpty(shopId)) {
                    User byPhone = userRepository.getByPhone(shopId);
                    long id = byPhone.getId();
                    sb.append(id + ",");
                }
            }
        }
        return sb.substring(0, sb.length() - 1);
    }
}
